package com.markerhub.controller;

import com.markerhub.common.lang.Result;
import com.markerhub.entity.TaskDevice;
import com.markerhub.service.TaskDeviceService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

/**
 * 任务设备Controller
 */
@Api(tags = "任务设备管理")
@RestController
@RequestMapping("/api/task-device")
public class TaskDeviceController extends BaseController {

    @Autowired
    private TaskDeviceService taskDeviceService;

    /**
     * 获取任务设备列表
     */
    @ApiOperation(value = "获取任务设备列表", notes = "获取所有任务设备信息，支持分页查询")
    @GetMapping
    public Result list(@RequestParam(required = false) Long taskId, @RequestParam(required = false) Long deviceId) {
        // 使用BaseController中的getPage()方法获取分页参数
        Page<TaskDevice> page = getPage();
        // 构建查询条件
        QueryWrapper<TaskDevice> wrapper = new QueryWrapper<>();
        if (taskId != null) {
            wrapper.eq("task_id", taskId);
        }
        if (deviceId != null) {
            wrapper.eq("device_id", deviceId);
        }
        // 按创建时间倒序排序
        wrapper.orderByDesc("created");
        // 执行分页查询
        Page<TaskDevice> pageData = taskDeviceService.page(page, wrapper);
        return Result.succ(200, "获取任务设备关联列表成功", pageData);
    }

    /**
     * 根据ID获取任务设备关联信息
     */
    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        TaskDevice taskDevice = taskDeviceService.getById(id);
        return Result.succ(200, "获取任务设备关联信息成功", taskDevice);
    }

    /**
     * 创建任务设备关联
     */
    @PostMapping
    public Result save(@RequestBody TaskDevice taskDevice) {
        boolean saved = taskDeviceService.save(taskDevice);
        return saved ? Result.succ(200, "创建任务设备关联成功", null) : Result.fail("创建任务设备关联失败");
    }

    /**
     * 更新任务设备关联
     */
    @PutMapping
    public Result update(@RequestBody TaskDevice taskDevice) {
        boolean updated = taskDeviceService.updateById(taskDevice);
        return updated ? Result.succ(200, "更新任务设备关联成功", null) : Result.fail("更新任务设备关联失败");
    }

    /**
     * 删除任务设备关联
     */
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        boolean deleted = taskDeviceService.removeById(id);
        return deleted ? Result.succ(200, "删除任务设备关联成功", null) : Result.fail("删除任务设备关联失败");
    }
}